package com.yeskery.nut.application.sun;

import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.spi.HttpServerProvider;
import com.yeskery.nut.application.NutServer;
import com.yeskery.nut.application.NutServerConfigure;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.logging.Logger;

/**
 * 基于JDK的HttpServer实现HTTP服务
 * @author sprout
 * 2022-05-19 10:31
 */
public class SunNutServer implements NutServer {

    /** 日志对象 */
    private static final Logger logger = Logger.getLogger(SunNutServer.class.getName());

    /** 等待队列大小 */
    protected static final int MAX_WAIT_SIZE = 5;

    /** 关机等待时间 */
    protected static final int MAX_WAIT_TIME = 5;

    /** Http 服务 */
    private HttpServer httpserver;

    @Override
    public void startServer(NutServerConfigure nutServerConfigure) throws Exception {
        HttpServerProvider provider = HttpServerProvider.provider();

        logger.info(getServerStartedTip(nutServerConfigure.getPort(), "SUN", false));
        httpserver = provider.createHttpServer(new InetSocketAddress(nutServerConfigure.getPort()), MAX_WAIT_SIZE);
        httpserver.setExecutor(nutServerConfigure.getNutApplication().getDefaultThreadPool().getThreadPool());
        httpserver.createContext("/", new ControllerHttpHandler(nutServerConfigure.getNutApplication(),
                nutServerConfigure.getServerContext(), nutServerConfigure.getDispatcher(),
                nutServerConfigure.getSessionManager(), nutServerConfigure.getServerRequestConfiguration(), this));
        httpserver.start();
    }

    @Override
    public void close() throws IOException {
        if (httpserver != null) {
            httpserver.stop(MAX_WAIT_TIME);
        }
    }
}
